/*! \file Device.cpp
 *	\brief 
 *
 *	created:	2009/11/13
 *	created:	13:11:2009   16:53
 *	filename: 	c:\src\main\libs\gd_dx9\Device.cpp
 *	file path:	c:\src\main\libs\gd_dx9
 *	file base:	Device
 *	file ext:	cpp
 *	author:		Vitalii Trubchaninov
 *				venngraydog@gmail.com
 */
 
#include "StdAfx.h"
#include "Device.h"

#include <app_win/Window.h>
#include <config/BaseConfig.h>
#include <core/exception.h>

#include "Driver.h"
//#include "PrimitiveBuilder.h"

namespace tt{
namespace gd_dx9{

Device::Device(Driver* driver, const SharedPtr<app_win::Window>& window)
: m_d3dDevice(NULL)
{
	assert(driver);
	assert(driver->d3dDriver());

	HWND mainWnd = window->hWnd();
	if (!mainWnd)
		TT_THROW(TEXT("driver->d3dDriver()->CreateDevice create failed! mainWnd == NULL"));

	bool fullScreen = window->fullscreen();
	app::WindowBounds bounds = window->bounds();
	app::WindowSize size = bounds.size();

	D3DFORMAT d3dFormat = fullScreen ? D3DFMT_X8R8G8B8 : D3DFMT_UNKNOWN;

	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.hDeviceWindow = mainWnd;
	d3dpp.Windowed = !fullScreen;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferCount = 2;
	d3dpp.BackBufferWidth = size.x;
	d3dpp.BackBufferHeight = size.y;
	d3dpp.BackBufferFormat = d3dFormat;

	HRESULT hr = driver->d3dDriver()->CreateDevice(
		D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		mainWnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&d3dpp, m_d3dDevice.getRef() );

	if( FAILED( hr ) )
		TT_THROW(TEXT("driver->d3dDriver()->CreateDevice create failed!"));
}

Device::~Device(void)
{
}

utils::COMPointer<IDirect3DDevice9>& Device::d3dDevice()
{
	return m_d3dDevice;
}

//////////////////////////////////////////////////////////////////////////
// void Device::onBeginScene()
// {
// 	m_d3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );
// 	m_d3dDevice->BeginScene();
// }
// 
// void Device::onEndScene()
// {
// 	m_d3dDevice->EndScene();
// }

void Device::onPresent()
{
	m_d3dDevice->Present(NULL, NULL, NULL, NULL);
}

SharedPtr<gd::DeviceContext> Device::onDeviceContext()
{
	return SharedPtr<gd::DeviceContext>();
}

SharedPtr<gd::PrimitiveBuilder> Device::onCreatePrimitiveBuilder()
{
//	return SharedPtr<gd::PrimitiveBuilder>(new PrimitiveBuilder(this));
	return SharedPtr<gd::PrimitiveBuilder>();
}

SharedPtr<gd::ShaderBuilder> Device::onCreateShaderBuilder()
{
	return SharedPtr<gd::ShaderBuilder>();
}

} //namespace gd_dx9
} //namespace tt
